import {Component, OnInit} from '@angular/core';
import {Http} from '@angular/http'
import 'rxjs/Rx'
import {Observable} from 'rxjs'
import {Router} from '@angular/router';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  formModel: FormGroup;
  fb: FormBuilder = new FormBuilder();

  dataSource: Observable<any>;
  responseErr: string;

  login() {
    this.responseErr = '';
    if (this.formModel.hasError('required', ['username'])) {
      this.responseErr = '账号是必填的';
    } else if (this.formModel.hasError('required', ['pwd'])) {
      this.responseErr = '密码是必填的';
    }
    if (this.formModel.valid) {
      const user = this.formModel.value;
      this.dataSource = this.http.post(`admin/login`, null, {params: user}).map(response => response.json());
      this.dataSource.subscribe(data => {
        if (data.code === 0) {
          sessionStorage.setItem('user', 'admin');
          this.router.navigate([''])
        } else {
          this.responseErr = data.msg
        }
      })
    }
  }

  constructor(public http: Http, private router: Router) {
    this.formModel = this.fb.group({
      username: ['', Validators.required],
      pwd: ['', [Validators.required]]
    })
  }

  ngOnInit() {
  }

}
